package com.pro.springbootshop.filter;

import com.pro.springbootshop.entity.Buyer;
import com.pro.springbootshop.exception.TokenAuthExpiredException;
import com.pro.springbootshop.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Slf4j
@Component
public class AuthHandlerInterceptor implements HandlerInterceptor {
    @Autowired
    TokenUtil tokenUtil;

    private String privateKey="shopOnline";
    private long yangToken=1000000L;
    private long oldToken=3000000000L;
    /**
     * 权限认证的拦截操作.
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        log.info("=======进入拦截器========");
        // 如果不是映射到方法直接通过,可以访问资源.
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        //为空就返回错误
        String token = httpServletRequest.getHeader("token");
        if (null == token || "".equals(token.trim())) {
            return false;
        }
        log.info("==============token:" + token);
        Map<String, String> map = tokenUtil.parseToken(token);
        String buyerId = map.get("buyerId");
        String buyerName = map.get("buyerName");
        String buyerAddress = map.get("buyerAddress");
        String buyerPhone = map.get("buyerPhone");
        long timeOfUse = System.currentTimeMillis() - Long.parseLong(map.get("timeStamp"));
        //1.判断 token 是否过期
        //年轻 token
        if (timeOfUse < yangToken) {
            log.info("年轻 token");
        }
        //老年 token 就刷新 token
        else if (timeOfUse >= yangToken && timeOfUse < oldToken) {
            Buyer buyer=new Buyer();
            buyer.setBuyerId(buyerId);
            buyer.setBuyerName(buyerName);
            buyer.setBuyerAddress(buyerAddress);
            buyer.setBuyerPhone(buyerPhone);
            httpServletResponse.setHeader("token",tokenUtil.getToken(buyer));
        }
        //过期 token 就返回 token 无效.
        else {
            throw new TokenAuthExpiredException();
        }

        return true;
    }

}
